//
//  VBUserAccountViewModel.swift
//  VBo
//
//  Created by 赵世得 on 2016/10/31.
//  Copyright © 2016年 Zh. All rights reserved.
//

import UIKit

class VBUserAccountViewModel{
    static let sharedTools: VBUserAccountViewModel = VBUserAccountViewModel()
    var userAccountModel: VBUserAccountModel?
    let filePath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
    var isLogin:Bool{
        return accessToken != nil
    }
    var accessToken: String?{
        if userAccountModel?.expires_Date?.compare(Date()) == ComparisonResult.orderedDescending{
            return userAccountModel?.access_token
        }else{
            return nil
        }
    }
    
    
    
    
    init() {
        userAccountModel = getUserAccountModel()
    }
}
extension VBUserAccountViewModel{
        //获取token
    func getUserAccount(code: String, finish: @escaping (Bool)->()){
        
            
            VBNetworkTools.sharedTools.oauthLoadUserAccount(code: code, sucsess: { (respones) in
                guard let res = respones as? [String: Any] else{
                    finish(false)
                    return
                }
                let userAccountModel = VBUserAccountModel.yy_model(withJSON: res)
                guard let model = userAccountModel else{
                    finish(false)
                    return
                }
                self.getUserInfo(model: model, finish: finish)
                print(userAccountModel)
                
                
            }) { (error) in
                finish(false)
                print(error)
            }
            
        }
        //用户信息
        func getUserInfo(model: VBUserAccountModel, finish: @escaping (Bool)->()){
            VBNetworkTools.sharedTools.oauthLoadUserInfo(model: model, sucsess: { (respones) in
                print(respones)
                guard let res = respones as? [String: Any] else{
                    finish(false)
                    return
                }
                model.screen_name = res["screen_name"] as? String
                model.avatar_large = res["avatar_large"] as? String
                print("model =",model)
                VBUserAccountViewModel.sharedTools.saveUserAccountModel(model: model)
                finish(true)
            }) { (error) in
                finish(false)
                print(error)
            }
            
        }
        
    }




extension VBUserAccountViewModel{
    func saveUserAccountModel(model: VBUserAccountModel){
        userAccountModel = model
        NSKeyedArchiver.archiveRootObject(model, toFile: filePath)
    }
    func getUserAccountModel()-> VBUserAccountModel?{
        let result = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? VBUserAccountModel
        return result
        
    }
    
}
